package com.gpj.netty.application.server;

import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @className BIOServer
 * @description BIO服务端代码
 *   * simple -- 最简单的BIO通信服务端代码
 *   * senior -- 常见的BIO通信服务端代码
 * @author GPJ
 * @date 2021/11/30 16:04
 * @version 1.0
 **/
@Slf4j
public class BIOServer {
	public static void main(String[] args) throws IOException {
//		NetWorkServer.simple();
		BIOServer.senior();
	}

	/**
	 * 最简单的BIO通信服务端代码
	 */
	public static void simple() throws IOException {
		ServerSocket serverSocket = new ServerSocket(9000);
		while (true){
			try {
				log.debug("等待连接...");
				Socket socket = serverSocket.accept();
				log.debug("接收到新的客户端连接");

				log.debug("准备读取数据...");
				byte[] bytes = new byte[1024];
				int num = socket.getInputStream().read(bytes);
				log.debug("客户端数据读取完毕");

				String msg = new String(bytes, 0, num);
				log.info("接收到客户端的数据：{}", msg);

				OutputStream out = socket.getOutputStream();
				out.write(("接收到请求[" + msg + "]").getBytes());
				out.flush();
			} catch (Exception e){
				log.error("服务异常：{}", e.toString(), e);
			}
		}
	}

	/**
	 * 常见的BIO通信服务端代码
	 */
	public static void senior() throws IOException {
		ServerSocket serverSocket = new ServerSocket(9000);
		while (true){
			log.debug("等待连接...");
			Socket socket = serverSocket.accept();
			log.debug("接收到新的客户端连接");

			new Thread(() -> {
				try {
					log.debug("准备读取数据...");
					InputStream in = socket.getInputStream();
					byte[] bytes = new byte[1024];
					int num = socket.getInputStream().read(bytes);
					log.debug("客户端数据读取完毕");

					log.info("接收到客户端的数据：{}", new String(bytes, 0, num));

					OutputStream out = socket.getOutputStream();
					out.write(("服务端接收到请求:{" + new String(bytes, 0, num) + "}").getBytes());
					out.flush();
				} catch (IOException e){
					log.error("服务异常：{}", e.toString(), e);
				}
			}).start();
		}
	}
}
